const fs = require('fs')
const unzip = require('node-unzip-2')

export class FileUtil {
  constructor() {}

  static mkdir(filePath) {
    const dirCache = {}
    const arr = filePath.split('/')
    let dir = arr[0]
    for (let i = 1; i < arr.length; i++) {
      if (!dirCache[dir] && !fs.existsSync(dir)) {
        dirCache[dir] = true
        fs.mkdirSync(dir)
      }
      dir = dir + '/' + arr[i]
    }
  }

  static writeFile(content, path) {
    if (fs.existsSync(path)) {
      fs.unlinkSync(path)
    }
    fs.writeFileSync(path, content)
  }

  static readFile(path) {
    if (!fs.existsSync(path)) {
      return ''
    } else {
      return fs.readFileSync(path, 'utf-8')
    }
  }

  static deleteFile(path) {
    if (fs.existsSync(path)) {
      fs.unlinkSync(path)
    }
  }

  static unzipFileAndRename(file, requireReName, isCurrentDir, successCallback, errorCallback) {
    let nodePath = require('path')
    let extractPath = file.substring(0, file.lastIndexOf('\\') + 1)
    let extract = null
    let tempDir = ''
    if (isCurrentDir) {
      let fileName = FileUtil.getFileNameByPath(file)
      fileName = fileName.substring(0, fileName.lastIndexOf('.'))
      tempDir = nodePath.join(extractPath, fileName)
      if (!fs.existsSync(tempDir)) {
        fs.mkdirSync(tempDir)
      }
      extract = unzip.Extract({
        path: tempDir,
      })
      try {
        fs.createReadStream(file).pipe(extract)
      } catch (error) {
        console.warn(error)
      }
    } else {
      extract = unzip.Extract({
        path: extractPath,
      })
      try {
        fs.createReadStream(file).pipe(extract)
      } catch (error) {
        console.warn(error)
      }
    }
    //如果解压失败则删除zip文件后重新下载
    extract.on('error', function(err) {
      const fs = require('fs')
      fs.unlink(tempDir, (error) => {
        console.log(tempDir);
        if (err) {
          console.log(error)
        }
        if (errorCallback) {
          errorCallback()
        }
      })
      console.log(err)

    })
    extract.on('finish', function() {
      if (requireReName) {
        if (tempDir) {
          setTimeout(function() {
            //500ms之后再去改名字，等待解压事件完成
            let url = tempDir
            fs.readdir(url, 'utf8', (err, fileList) => {
              if (err) {
                console.log(err)
                if (errorCallback) {
                  errorCallback()
                }
              }
              for (let i = 0; i < fileList.length; i++) {
                //获取文件后缀名
                let type = FileUtil.getFileExtensionByPath(fileList[i])
                let fileName = fileList[i].substring(0, fileList[i].length - type.length)
                type = type.toLowerCase()
                if (type === '.mp4') {
                  type = '.bosm'
                } else if (type === '.png') {
                  type = '.bosp'
                } else if (type === '.jpg') {
                  type = '.bosj'
                }
                //新名称,根据需求修改名称，可以使用正则等等
                let newName = fileName + type
                try {
                  fs.renameSync(nodePath.resolve(url, fileList[i]), nodePath.resolve(url, newName))
                } catch (error) {
                  console.log(error)
                }
              }
              if (successCallback) {
                successCallback()
              }
              console.log('第一次执行修改文件后缀操作结束...')
            })
          }, 500)

          //为了确保修改文件名称成功，需要再执行一次，10s钟之后再执行一次
          setTimeout(function() {
            let url = tempDir
            fs.readdir(url, 'utf8', (err, fileList) => {
              if (err) console.log(err)
              for (let i = 0; i < fileList.length; i++) {
                //获取文件后缀名
                let type = FileUtil.getFileExtensionByPath(fileList[i])
                let fileName = fileList[i].substring(0, fileList[i].length - type.length)
                if (type === '.mp4') {
                  type = '.bosm'
                } else if (type === '.png') {
                  type = '.bosp'
                } else if (type === '.jpg') {
                  type = '.bosj'
                }
                //新名称,根据需求修改名称，可以使用正则等等
                let newName = fileName + type
                try {
                  fs.renameSync(nodePath.resolve(url, fileList[i]), nodePath.resolve(url, newName))
                } catch (error) {
                  console.log(error)
                }
              }
              console.log('第二次执行修改文件后缀操作结束...')
            })
          }, 10 * 1000)
        } else {
          if (successCallback) {
            successCallback()
          }
        }
      } else {
        if (successCallback) {
          successCallback()
        }
      }
    })
  }

  static getFileNameByPath(path) {
    let nodePath = require('path')
    let index = path.lastIndexOf(nodePath.sep) // lastIndexOf("/")  找到最后一个  /  的位置
    let fileName = path.substr(index + 1) // substr() 截取剩余的字符，即得文件名xxx.doc

    return fileName
  }

  static getFileTypeByPath(path) {
    let index = path.lastIndexOf('.') // lastIndexOf("/")  找到最后一个  /  的位置
    let fileType = path.substr(index + 1) // substr() 截取剩余的字符，即文件名doc

    return fileType
  }

  static getFileExtensionByPath(path) {
    let index1 = path.lastIndexOf('.') // lastIndexOf("/")  找到最后一个  /  的位置
    let index2 = path.length
    let fileExtension = path.substr(index1, index2) // substr() 截取剩余的字符，即文件名.doc

    return fileExtension
  }

  static copyDirectory(src, dest, isZip = false, callback) {
    const path = require('path')
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest)
    }
    if (!fs.existsSync(src)) {
      return false
    }
    // console.log("src:" + src + ", dest:" + dest);
    // 拷贝新的内容进去
    let dirs = fs.readdirSync(src)
    for (let i = 0; i < dirs.length; i++) {
      let item_path = path.join(src, dirs[i])
      let temp = fs.statSync(item_path)
      if (temp.isFile()) {
        // 是文件
        console.log('Item Is File:' + dirs[i])
        let dest_path = path.join(dest, dirs[i])
        if (fs.existsSync(dest_path)) {
          fs.unlinkSync(dest_path)
        }
        if (isZip) {
          if (FileUtil.getFileTypeByPath(item_path) === 'zip') {
            fs.copyFileSync(item_path, dest_path)
            if (dest_path.indexOf('PolyvVideo') !== -1) {
              //保利威视
              FileUtil.unzipFileAndRename(dest_path, false, false, callback, callback)
            } else {
              FileUtil.unzipFileAndRename(dest_path, true, true, callback, callback)
            }
          }
          if (FileUtil.getFileNameByPath(item_path) === 'thumb' || FileUtil.getFileTypeByPath(item_path) === 'ppt') {
            fs.copyFileSync(item_path, dest_path)
          }
        } else {
          fs.copyFileSync(item_path, dest_path)
        }
      } else if (temp.isDirectory()) {
        // 是目录
        // console.log("Item Is Directory:" + dirs[i]);
        FileUtil.copyDirectory(item_path, path.join(dest, dirs[i]), isZip, callback)
      }
    }
  }

  /**
   * 统计所有zip包地址
   * @param {*} destPathes
   */
  static staticsZipInfo(src, dest, isZip = false, destPathes, pathMap) {
    if (!(destPathes instanceof Array)) {
      return false
    }
    const path = require('path')
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest)
    }
    if (!fs.existsSync(src)) {
      return false
    }
    // console.log("src:" + src + ", dest:" + dest);
    // 拷贝新的内容进去
    let dirs = fs.readdirSync(src)
    for (let i = 0; i < dirs.length; i++) {
      let item_path = path.join(src, dirs[i])
      let temp = fs.statSync(item_path)
      if (temp.isFile()) {
        // 是文件
        console.log('Item Is File:' + dirs[i])
        let dest_path = path.join(dest, dirs[i])
        pathMap.set(item_path, dest_path)
        if (fs.existsSync(dest_path)) {
          fs.unlinkSync(dest_path)
        }
        if (isZip) {
          if (FileUtil.getFileTypeByPath(item_path) === 'zip') {
            if (dest_path.indexOf('PolyvVideo') !== -1) {
              //保利威视
              // FileUtil.unzipFileAndRename(dest_path, false, false);
              destPathes.push(dest_path)
            } else {
              // FileUtil.unzipFileAndRename(dest_path, true, true);
              destPathes.push(dest_path)
            }
          }
          if (FileUtil.getFileNameByPath(item_path) === 'thumb' || FileUtil.getFileTypeByPath(item_path) === 'ppt') {
            // destPathes.push(dest_path);
          }
        } else {
          // destPathes.push(dest_path);
        }
      } else if (temp.isDirectory()) {
        // 是目录
        // console.log("Item Is Directory:" + dirs[i]);
        FileUtil.staticsZipInfo(item_path, path.join(dest, dirs[i]), isZip, destPathes, pathMap)
      }
    }
  }
}
